package day13.joinDemo;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 通过案例来使用Thread的join()方法
 * 多个线程查询飞机航班信息
 */
public class FlyDemo {

    public static List<String> fightCompany = Arrays.asList("西藏航空", "天津航空", "成都航空");

    public static void main(String[] args) {
        List<String> results = search("CD", "LZ");
        System.out.println("===========结果===========");
        results.forEach(System.out::println);
    }

    public static List<String> search(String original, String dest) {
        final List<String> result = new ArrayList<>();

        List<FlyInfoQueryTask> infoQueryTasks =
                fightCompany.stream().map(f -> createSearchTask(f, original, dest)).collect(Collectors.toList());

        infoQueryTasks.forEach(Thread::start);

        infoQueryTasks.forEach(t -> {
            try {
                t.join();
            } catch (InterruptedException exception) {
                exception.printStackTrace();
            }
        });
        // 加入返回结果中
        infoQueryTasks.stream().map(FlyInfoQueryTask::get).forEach(result::addAll);
        return result;
    }

    public static FlyInfoQueryTask createSearchTask(String company, String original, String dest) {
        return new FlyInfoQueryTask(company, original, dest);
    }

}
